<template>
  <div class="game-container">
    <!-- 顶部导航栏 -->
    <nav class="navbar">
      <div class="logo">贪吃蛇大作战</div>
      <div class="nav-actions">
        <div v-if="!isLoggedIn" class="guest-actions">
          <button @click="showLoginModal">登录</button>
          <button @click="showRegisterModal">注册</button>
        </div>
        <div v-else class="user-actions">
          <span class="user-info">{{ currentUser.username }}</span>
          <span class="user-stats">击杀: {{ currentUser.kills || 0 }} | 排名: {{ getRank() }}</span>
          <button @click="logout">退出</button>
        </div>
      </div>
    </nav>

    <!-- 游戏标题和模式选择 -->
    <div class="header">
      <h1>贪吃蛇大作战</h1>
      <div class="game-modes">
        <button @click="setMode('single')" :class="{ active: mode === 'single' }">单人模式</button>
        <button @click="setMode('battle')" :class="{ active: mode === 'battle' }">竞技模式</button>
        <button @click="setMode('god')" :class="{ active: mode === 'god' }">无敌模式</button>
        <button @click="setMode('speed')" :class="{ active: mode === 'speed' }">速成模式</button>
      </div>
    </div>

    <!-- 游戏状态显示 -->
    <div class="status">
      <div v-if="mode === 'single' || mode === 'god' || mode === 'speed'">
        得分: {{ score }} | 长度: {{ snakes[0].length }} | 生命: {{ lives }} | 击杀: {{ kills }}
      </div>
      <div v-else-if="mode === 'battle'">
        <div class="player-info">玩家: {{ score }}分 | 长度: {{ snakes[0].length }} | 击杀: {{ kills }}</div>
        <div class="enemy-count">场上敌人: {{ enemySnakes.length }}</div>
      </div>
    </div>

    <!-- 游戏设置 -->
    <div class="settings">
      <div class="skin-select">
        <label>蛇皮肤:</label>
        <select v-model="currentSkin">
          <option v-for="(skin, index) in snakeSkins" :key="index" :value="index">{{ skin.name }}</option>
        </select>
      </div>
      <div class="speed-select" v-if="mode !== 'god' && mode !== 'speed'">
        <label>游戏速度:</label>
        <select v-model="gameSpeed">
          <option value="250">慢</option>
          <option value="200" selected>中</option>
          <option value="150">快</option>
          <option value="100">极快</option>
        </select>
      </div>
      <div class="battle-settings" v-if="mode === 'battle'">
        <label>敌人生成间隔:</label>
        <select v-model="battleSpawnInterval">
          <option value="8000">8秒</option>
          <option value="6000" selected>6秒</option>
          <option value="4000">4秒</option>
        </select>
      </div>
    </div>

    <!-- 游戏棋盘 -->
    <div class="game-board" :style="boardStyle">
      <!-- 渲染玩家蛇 -->
      <div v-for="(snake, snakeIndex) in snakes" :key="snakeIndex">
        <div v-for="(segment, index) in snake" :key="index" class="snake-segment"
          :style="getSnakeStyle(segment, snakeIndex, index, 'player', isInvincible)"></div>
      </div>

      <!-- 渲染敌人蛇 -->
      <div v-for="(enemy, enemyIndex) in enemySnakes" :key="enemyIndex">
        <div v-for="(segment, index) in enemy.snake" :key="index" class="snake-segment"
          :style="getSnakeStyle(segment, enemyIndex, index, 'enemy', enemy.protectionTimer > 0)"></div>
      </div>

      <!-- 渲染食物 -->
      <div v-for="(food, index) in foods" :key="index" class="food" :style="getFoodStyle(food)" :class="food.type">{{
        food.icon }}</div>
    </div>

    <!-- 游戏控制 -->
    <div class="controls">
      <button @click="startGame">开始游戏</button>
      <button @click="pauseGame" :disabled="!isRunning">{{ isRunning ? '暂停' : '继续' }}</button>
      <button @click="resetGame">重置游戏</button>
    </div>

    <!-- 操作说明 -->
    <div class="instructions">
      <div v-if="mode === 'single' || mode === 'god' || mode === 'speed'">
        <p>方向键: ↑↓←→ 控制移动</p>
      </div>
      <div v-else-if="mode === 'battle'">
        <p>方向键: ↑↓←→ 控制移动 | 击杀其他蛇获得高分</p>
        <p>注意: 新生成的蛇有保护时间，无法被攻击</p>
      </div>
    </div>

    <!-- 排行榜 -->
    <div class="leaderboard">
      <h3>竞技排行榜</h3>
      <ol>
        <li v-for="(player, index) in leaderboard" :key="index" :class="index < 3 ? 'top-score' : ''">
          {{ index + 1 }}. {{ player.name }} - {{ player.score }}分 | 击杀: {{ player.kills }}
        </li>
      </ol>
    </div>

    <!-- 登录模态框 -->
    <div v-if="showLogin" class="modal">
      <div class="modal-content">
        <h2>登录</h2>
        <input type="text" v-model="loginUsername" placeholder="用户名">
        <input type="password" v-model="loginPassword" placeholder="密码">
        <button @click="login">登录</button>
        <button @click="showLogin = false">取消</button>
      </div>
    </div>

    <!-- 注册模态框 -->
    <div v-if="showRegister" class="modal">
      <div class="modal-content">
        <h2>注册</h2>
        <input type="text" v-model="registerUsername" placeholder="用户名">
        <input type="password" v-model="registerPassword" placeholder="密码">
        <button @click="register">注册</button>
        <button @click="showRegister = false">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
  import { ref, reactive, computed, onMounted, onBeforeUnmount, watch } from 'vue'

  export default {
    setup() {
      // 游戏基础状态
      const mode = ref('single') // 游戏模式: 单人、竞技、无敌、速成
      const isRunning = ref(false)
      const gridSize = ref(25)
      const gameSpeed = ref(200) // 游戏速度(毫秒)
      const lives = ref(3)
      const score = ref(0)
      const kills = ref(0)
      const battleSpawnInterval = ref(6000) // 竞技模式生成间隔(毫秒)
      const protectionTime = ref(3000) // 保护时间(毫秒)
      const isInvincible = ref(false) // 无敌状态
      const invincibleTimer = ref(null) // 无敌计时器

      // 玩家蛇数据
      const snakes = reactive([
        [{ x: 10, y: 10 }] // 玩家蛇
      ])

      // 敌人蛇数据
      const enemySnakes = reactive([])

      // 蛇移动方向
      const direction = ref('right')

      // 敌人蛇方向和保护状态
      const enemyDirections = reactive([])
      const enemyProtectionTimers = reactive([])

      // 食物数据
      const foods = reactive([])
      const foodTypes = [
        { type: 'normal', icon: '🍎', score: 10, effect: 'normal', color: '#FF5252' },
        { type: 'speed', icon: '⚡', score: 20, effect: 'speed', color: '#FFEB3B' },
        { type: 'grow', icon: '🌱', score: 15, effect: 'grow', color: '#4CAF50' },
        { type: 'poison', icon: '💀', score: -5, effect: 'poison', color: '#9C27B0' },
        { type: 'life', icon: '❤️', score: 0, effect: 'life', color: '#E91E63' },
        { type: 'invincible', icon: '✨', score: 0, effect: 'invincible', color: '#FFD700' }, // 金手指
        { type: 'shrink', icon: '🍄', score: -10, effect: 'shrink', color: '#9932CC' }, // 缩小蘑菇
        { type: 'enlarge', icon: '🍄', score: 10, effect: 'enlarge', color: '#FF69B4' } // 变大蘑菇
      ]

      // 动物皮肤数据
      const snakeSkins = [
        { name: '经典绿蛇', head: '🐍', headColor: '#4CAF50', bodyColor: '#8BC34A', size: 1 },
        { name: '猫咪皮肤', head: '😺', headColor: '#FFC107', bodyColor: '#FFEE58', size: 1 },
        { name: '狗狗皮肤', head: '🐶', headColor: '#2196F3', bodyColor: '#64B5F6', size: 1 },
        { name: '狼皮肤', head: '🐺', headColor: '#9E9E9E', bodyColor: '#757575', size: 1 },
        { name: '哆啦A梦', head: '🤖', headColor: '#00BCD4', bodyColor: '#00ACC1', size: 1 },
        { name: '蜡笔小新', head: '🧑', headColor: '#FF5722', bodyColor: '#F44336', size: 1 },
        { name: '熊大', head: '🐻', headColor: '#E53935', bodyColor: '#F44336', size: 1.2 },
        { name: '熊二', head: '🐻', headColor: '#FFC107', bodyColor: '#FFEB3B', size: 1.2 },
        { name: '光头强', head: '👨', headColor: '#2196F3', bodyColor: '#64B5F6', size: 1 }
      ]
      const currentSkin = ref(0)

      // 游戏循环
      const gameLoop = ref(null)
      const enemySpawnLoop = ref(null)
      const effectLoop = ref(null)

      // 排行榜数据
      const leaderboard = ref([])

      // 账号系统状态
      const isLoggedIn = ref(false)
      const currentUser = ref(null)
      const showLogin = ref(false)
      const showRegister = ref(false)
      const loginUsername = ref('')
      const loginPassword = ref('')
      const registerUsername = ref('')
      const registerPassword = ref('')

      // 计算棋盘样式（原神风格背景）
      const boardStyle = computed(() => ({
        width: `${gridSize.value * 30}px`,
        height: `${gridSize.value * 30}px`,
        border: '2px solid #333',
        position: 'relative',
        margin: '20px auto',
        overflow: 'hidden',
        // 原神风格渐变背景
        background: 'linear-gradient(135deg, #4361EE 0%, #3A0CA3 30%, #7209B7 60%, #F72585 100%)'
      }))

      // 生成食物（根据模式调整生成数量）
      const spawnFood = () => {
        // 速成模式生成更多食物
        const foodCount = mode.value === 'speed' ? 2 : 1
        for (let i = 0; i < foodCount; i++) {
          const randomType = Math.floor(Math.random() * foodTypes.length)
          const food = {
            x: Math.floor(Math.random() * gridSize.value),
            y: Math.floor(Math.random() * gridSize.value),
            ...foodTypes[randomType]
          }

          // 确保食物不在蛇身上
          const isOnSnake = [...snakes[0], ...enemySnakes.flatMap(e => e.snake)].some(seg =>
            seg.x === food.x && seg.y === food.y
          )

          if (isOnSnake) {
            spawnFood()
            continue
          }

          foods.push(food)
        }
      }

      // 生成敌人蛇
      const spawnEnemySnake = () => {
        if (mode.value !== 'battle' || enemySnakes.length >= 5) return

        // 随机位置
        let x, y
        do {
          x = Math.floor(Math.random() * gridSize.value)
          y = Math.floor(Math.random() * gridSize.value)
        } while (
          snakes[0].some(seg => seg.x === x && seg.y === y) ||
          enemySnakes.flatMap(e => e.snake).some(seg => seg.x === x && seg.y === y)
        )

        // 初始长度
        const length = Math.floor(Math.random() * 3) + 3
        const enemySnake = {
          snake: Array(length).fill().map((_, i) => ({ x: x - i, y })),
          direction: getRandomDirection(),
          protectionTimer: protectionTime.value // 保护时间
        }

        enemySnakes.push(enemySnake)
        enemyDirections.push(getRandomDirection())
        enemyProtectionTimers.push(protectionTime.value)
      }

      // 获取随机方向
      const getRandomDirection = () => {
        const directions = ['up', 'down', 'left', 'right']
        return directions[Math.floor(Math.random() * directions.length)]
      }

      // 检查碰撞
      const checkCollision = (head, isEnemy = false, isProtected = false) => {
        if (mode.value === 'god' || isInvincible.value) return false // 无敌模式/无敌状态无碰撞

        // 边界碰撞
        if (head.x < 0 || head.x >= gridSize.value || head.y < 0 || head.y >= gridSize.value) {
          return true
        }

        // 自身碰撞
        if (snakes[0].some((seg, index) => index > 0 && seg.x === head.x && seg.y === head.y)) {
          return true
        }

        // 与敌人蛇碰撞
        for (let i = 0; i < enemySnakes.length; i++) {
          const enemy = enemySnakes[i]
          if (enemy.protectionTimer > 0 && isProtected) continue // 保护期不碰撞

          // 头部碰撞敌人头部
          if (enemy.snake[0].x === head.x && enemy.snake[0].y === head.y) {
            if (snakes[0].length >= enemy.snake.length) {
              // 玩家胜利，击杀敌人
              kills.value++
              enemySnakes.splice(i, 1)
              enemyDirections.splice(i, 1)
              enemyProtectionTimers.splice(i, 1)
              score.value += enemy.snake.length * 5
              return false
            } else {
              // 玩家失败
              return true
            }
          }

          // 碰撞敌人身体
          if (enemy.snake.some((seg, index) => index > 0 && seg.x === head.x && seg.y === head.y)) {
            return true
          }
        }

        return false
      }

      // 移动蛇
      const moveSnake = () => {
        const snake = snakes[0]
        const head = { ...snake[0] }

        // 更新头部位置
        switch (direction.value) {
          case 'up': head.y--; break
          case 'down': head.y++; break
          case 'left': head.x--; break
          case 'right': head.x++; break
        }

        // 检查碰撞
        if (checkCollision(head)) {
          lives.value--
          if (lives.value <= 0) {
            gameOver()
          } else {
            resetSnake()
          }
          return
        }

        // 检查食物碰撞
        let ateFood = false
        foods.forEach((food, index) => {
          if (head.x === food.x && head.y === food.y) {
            // 应用食物效果
            applyFoodEffect(food.effect)

            // 更新分数
            score.value += food.score

            // 移除食物并生成新食物
            foods.splice(index, 1)
            setTimeout(spawnFood, 300)
            ateFood = true
          }
        })

        // 如果没吃到食物，移除尾部
        if (!ateFood) {
          snake.pop()
        }

        // 添加新头部
        snake.unshift(head)
      }

      // 移动敌人蛇
      const moveEnemySnakes = () => {
        for (let i = 0; i < enemySnakes.length; i++) {
          const enemy = enemySnakes[i]
          const head = { ...enemy.snake[0] }

          // 随机改变方向
          if (Math.random() < 0.05) {
            enemy.direction = getRandomDirection()
          }

          // 更新头部位置
          switch (enemy.direction) {
            case 'up': head.y--; break
            case 'down': head.y++; break
            case 'left': head.x--; break
            case 'right': head.x++; break
          }

          const isProtected = enemy.protectionTimer > 0
          if (checkCollision(head, true, isProtected)) {
            // 敌人碰撞，移除敌人
            enemySnakes.splice(i, 1)
            enemyDirections.splice(i, 1)
            enemyProtectionTimers.splice(i, 1)
            continue
          }

          // 敌人吃食物
          let ateFood = false
          foods.forEach((food, index) => {
            if (head.x === food.x && head.y === food.y) {
              applyEnemyFoodEffect(i, food.effect)
              foods.splice(index, 1)
              setTimeout(spawnFood, 300)
              ateFood = true
            }
          })

          // 如果没吃到食物，移除尾部
          if (!ateFood) {
            enemy.snake.pop()
          }

          // 添加新头部
          enemy.snake.unshift(head)
        }
      }

      // 应用玩家食物效果
      const applyFoodEffect = (effect) => {
        switch (effect) {
          case 'speed':
            // 临时加速
            const originalSpeed = gameSpeed.value
            gameSpeed.value = Math.max(50, originalSpeed - 50)
            setTimeout(() => {
              gameSpeed.value = originalSpeed
            }, 5000)
            break
          case 'grow':
            // 增长3段
            for (let i = 0; i < 3; i++) {
              snakes[0].push({ ...snakes[0][snakes[0].length - 1] })
            }
            break
          case 'poison':
            // 减少长度
            const length = snakes[0].length
            if (length > 3) {
              snakes[0].splice(Math.max(3, length - 3), length - 3)
            }
            break
          case 'life':
            // 增加生命
            lives.value++
            break
          case 'invincible':
            // 无敌状态
            isInvincible.value = true
            clearInterval(invincibleTimer.value)
            invincibleTimer.value = setInterval(() => {
              isInvincible.value = false
              clearInterval(invincibleTimer.value)
            }, 3000) // 3秒无敌
            break
          case 'shrink':
            // 缩小蛇
            const shrinkLength = Math.max(3, snakes[0].length / 2)
            snakes[0].splice(0, snakes[0].length - shrinkLength)
            break
          case 'enlarge':
            // 放大蛇
            const originalLength = snakes[0].length
            for (let i = 0; i < originalLength; i++) {
              snakes[0].push({ ...snakes[0][snakes[0].length - 1] })
            }
            break
        }
      }

      // 应用敌人食物效果
      const applyEnemyFoodEffect = (enemyIndex, effect) => {
        const enemy = enemySnakes[enemyIndex]
        switch (effect) {
          case 'speed':
            // 敌人加速
            break
          case 'grow':
            // 敌人增长2段
            for (let i = 0; i < 2; i++) {
              enemy.snake.push({ ...enemy.snake[enemy.snake.length - 1] })
            }
            break
          case 'poison':
            // 敌人减少长度
            const length = enemy.snake.length
            if (length > 3) {
              enemy.snake.splice(Math.max(3, length - 2), length - 2)
            }
            break
        }
      }

      // 重置蛇的位置
      const resetSnake = () => {
        snakes[0].splice(0, snakes[0].length, { x: 10, y: 10 })
      }

      // 游戏结束
      const gameOver = () => {
        clearInterval(gameLoop.value)
        clearInterval(enemySpawnLoop.value)
        clearInterval(effectLoop.value)
        isRunning.value = false

        // 保存到排行榜
        if (score.value > 0) {
          const playerName = isLoggedIn.value ? currentUser.value.username : prompt('游戏结束！请输入你的名字:', '玩家')
          if (playerName) {
            saveToLeaderboard({ name: playerName, score: score.value, kills: kills.value })
            leaderboard.value = loadLeaderboard()

            if (isLoggedIn.value) {
              saveUserScore(score.value, kills.value)
            }
          }
        }
      }

      // 开始游戏
      const startGame = () => {
        if (isRunning.value) return

        // 重置游戏状态
        resetGame()

        // 生成初始食物
        for (let i = 0; i < 5; i++) {
          spawnFood()
        }

        // 启动游戏循环
        gameLoop.value = setInterval(() => {
          moveSnake()
          if (mode.value === 'battle') {
            moveEnemySnakes()
          }
        }, gameSpeed.value)

        // 竞技模式生成敌人蛇
        if (mode.value === 'battle') {
          enemySpawnLoop.value = setInterval(spawnEnemySnake, battleSpawnInterval.value)
        }

        isRunning.value = true
      }

      // 暂停游戏
      const pauseGame = () => {
        if (!isRunning.value) return

        isRunning.value = false
        clearInterval(gameLoop.value)
        clearInterval(enemySpawnLoop.value)
        clearInterval(effectLoop.value)
      }

      // 重置游戏
      const resetGame = () => {
        clearInterval(gameLoop.value)
        clearInterval(enemySpawnLoop.value)
        clearInterval(effectLoop.value)
        clearInterval(invincibleTimer.value)

        // 重置蛇
        snakes[0].splice(0, snakes[0].length, { x: 10, y: 10 })

        // 重置敌人蛇
        enemySnakes.splice(0, enemySnakes.length)
        enemyDirections.splice(0, enemyDirections.length)
        enemyProtectionTimers.splice(0, enemyProtectionTimers.length)

        // 重置分数和生命
        score.value = 0
        kills.value = 0
        lives.value = 3
        isInvincible.value = false

        // 重置方向
        direction.value = 'right'

        // 清空食物
        foods.splice(0, foods.length)

        isRunning.value = false
      }

      // 设置游戏模式
      const setMode = (newMode) => {
        mode.value = newMode
        resetGame()

        // 速成模式调整速度和食物生成
        if (newMode === 'speed') {
          gameSpeed.value = 50
        } else {
          gameSpeed.value = 200
        }
      }

      // 获取蛇的样式
      const getSnakeStyle = (segment, snakeIndex, index, type, isProtected = false) => {
        let skin = snakeSkins[currentSkin.value]
        if (type === 'enemy') {
          // 敌人蛇使用随机皮肤
          skin = snakeSkins[Math.floor(Math.random() * snakeSkins.length)]
        }

        const isHead = index === 0
        const size = skin.size || 1

        let borderRadius = '0'
        if (isHead) {
          borderRadius = '15px 15px 0 0'
        }

        return {
          left: `${segment.x * 30}px`,
          top: `${segment.y * 30}px`,
          width: `${28 * size}px`,
          height: `${28 * size}px`,
          position: 'absolute',
          background: isHead ? skin.headColor : skin.bodyColor,
          borderRadius,
          zIndex: isHead ? 2 : 1,
          transition: 'all 0.1s',
          // 无敌状态效果
          boxShadow: isInvincible.value && type === 'player' ? '0 0 10px #FFD700, 0 0 20px #FFD700' : '',
          // 保护期效果
          border: isProtected ? '2px solid #9C27B0' : 'none'
        }
      }

      // 获取食物样式
      const getFoodStyle = (food) => ({
        left: `${food.x * 30}px`,
        top: `${food.y * 30}px`,
        position: 'absolute',
        fontSize: '24px',
        zIndex: 3,
        animation: 'pulse 1s infinite',
        color: food.color
      })

      // 生命周期钩子
      onMounted(() => {
        // 加载排行榜
        leaderboard.value = loadLeaderboard()

        // 键盘控制
        window.addEventListener('keydown', (e) => {
          if (!isRunning.value) return

          const dirMap = {
            ArrowUp: 'up',
            ArrowDown: 'down',
            ArrowLeft: 'left',
            ArrowRight: 'right'
          }
          if (dirMap[e.key]) {
            e.preventDefault()
            changeDirection(dirMap[e.key])
          }
        })

        // 监听模式变化调整食物生成
        watch(mode, (newMode) => {
          if (newMode === 'speed') {
            gameSpeed.value = 50
          } else {
            gameSpeed.value = 200
          }
        })
      })

      // 改变方向
      const changeDirection = (newDir) => {
        const opposite = {
          up: 'down',
          down: 'up',
          left: 'right',
          right: 'left'
        }

        // 不能反向移动
        if (newDir !== opposite[direction.value]) {
          direction.value = newDir
        }
      }

      // 卸载组件时清理
      onBeforeUnmount(() => {
        clearInterval(gameLoop.value)
        clearInterval(enemySpawnLoop.value)
        clearInterval(effectLoop.value)
        clearInterval(invincibleTimer.value)
        window.removeEventListener('keydown', null)
      })

      // 排行榜操作
      const loadLeaderboard = () => {
        try {
          const data = localStorage.getItem('snakeLeaderboard')
          return data ? JSON.parse(data) : []
        } catch (e) {
          return []
        }
      }

      const saveToLeaderboard = (player) => {
        try {
          const leaderboard = loadLeaderboard()
          leaderboard.push(player)
          leaderboard.sort((a, b) => b.score - a.score)
          leaderboard.splice(10) // 只保留前10名
          localStorage.setItem('snakeLeaderboard', JSON.stringify(leaderboard))
        } catch (e) {
          console.error('Failed to save leaderboard', e)
        }
      }

      // 账号系统 - 登录
      const login = () => {
        if (!loginUsername.value || !loginPassword.value) {
          alert('用户名和密码不能为空')
          return
        }

        const users = JSON.parse(localStorage.getItem('snakeUsers') || '[]')
        const user = users.find(u =>
          u.username === loginUsername.value && u.password === loginPassword.value
        )

        if (user) {
          isLoggedIn.value = true
          currentUser.value = user
          showLogin.value = false
          leaderboard.value = loadLeaderboard()
        } else {
          alert('用户名或密码错误')
        }
      }

      // 账号系统 - 注册
      const register = () => {
        if (!registerUsername.value || !registerPassword.value) {
          alert('用户名和密码不能为空')
          return
        }

        const users = JSON.parse(localStorage.getItem('snakeUsers') || '[]')
        const existingUser = users.find(u => u.username === registerUsername.value)

        if (existingUser) {
          alert('用户名已存在')
          return
        }

        const newUser = {
          id: Date.now(),
          username: registerUsername.value,
          password: registerPassword.value,
          scores: []
        }

        users.push(newUser)
        localStorage.setItem('snakeUsers', JSON.stringify(users))

        alert('注册成功，请登录')
        showRegister.value = false
        showLogin.value = true
      }

      // 账号系统 - 退出
      const logout = () => {
        isLoggedIn.value = false
        currentUser.value = null
      }

      // 保存用户成绩
      const saveUserScore = (score, kills) => {
        if (!currentUser.value) return

        const users = JSON.parse(localStorage.getItem('snakeUsers') || '[]')
        const userIndex = users.findIndex(u => u.id === currentUser.value.id)

        if (userIndex !== -1) {
          users[userIndex].scores.push({
            score,
            kills,
            date: new Date().toISOString()
          })

          // 只保留最高的5个分数
          users[userIndex].scores.sort((a, b) => b.score - a.score)
          if (users[userIndex].scores.length > 5) {
            users[userIndex].scores = users[userIndex].scores.slice(0, 5)
          }

          localStorage.setItem('snakeUsers', JSON.stringify(users))
          currentUser.value = users[userIndex]
        }
      }

      // 获取当前用户排名
      const getRank = () => {
        if (!isLoggedIn.value || !leaderboard.value.length) return '未登录'

        const userScore = currentUser.value.scores.length > 0
          ? Math.max(...currentUser.value.scores.map(s => s.score))
          : 0

        const rank = leaderboard.value.findIndex(p => p.name === currentUser.value.username) + 1
        return rank > 0 ? rank : '未进入前10'
      }

      // 暴露给模板
      return {
        mode,
        isRunning,
        snakes,
        score,
        kills,
        lives,
        foods,
        enemySnakes,
        boardStyle,
        snakeSkins,
        currentSkin,
        gameSpeed,
        battleSpawnInterval,
        leaderboard,
        startGame,
        pauseGame,
        resetGame,
        setMode,
        getSnakeStyle,
        getFoodStyle,
        isLoggedIn,
        currentUser,
        showLogin,
        showRegister,
        loginUsername,
        loginPassword,
        registerUsername,
        registerPassword,
        login,
        register,
        logout,
        getRank
      }
    }
  }
</script>

<style scoped>
  .game-container {
    font-family: 'Arial', sans-serif;
    text-align: center;
    max-width: 900px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f0f0f0;
    border-radius: 10px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  }

  .header {
    margin-bottom: 20px;
  }

  h1 {
    color: #333;
    margin-bottom: 10px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .game-modes {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-bottom: 20px;
  }

  button {
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  }

  button:hover {
    background-color: #45a049;
    transform: translateY(-2px);
  }

  button.active {
    background-color: #2196F3;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  }

  .status {
    font-size: 18px;
    margin-bottom: 15px;
    display: flex;
    justify-content: center;
    gap: 20px;
    font-weight: bold;
    color: #333;
  }

  .player-info {
    font-size: 18px;
  }

  .enemy-count {
    margin-top: 5px;
    color: #F44336;
    font-weight: bold;
  }

  .settings {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-bottom: 20px;
  }

  .skin-select,
  .speed-select,
  .battle-settings {
    display: flex;
    align-items: center;
    gap: 10px;
    background-color: white;
    padding: 10px 15px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  select {
    padding: 5px 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
    appearance: none;
    background-color: white;
  }

  .game-board {
    background-color: #f0f0f0;
    position: relative;
    overflow: hidden;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  }

  .snake-segment {
    position: absolute;
    transition: all 0.1s;
  }

  .food {
    position: absolute;
    font-size: 24px;
    animation: pulse 1s infinite;
    text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
      opacity: 1;
    }

    50% {
      transform: scale(1.1);
      opacity: 0.8;
    }

    100% {
      transform: scale(1);
      opacity: 1;
    }
  }

  .controls {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  .instructions {
    margin-top: 15px;
    font-size: 14px;
    color: #666;
    max-width: 600px;
    margin-left: auto;
    margin-right: auto;
  }

  .leaderboard {
    margin-top: 30px;
    padding: 15px;
    border-radius: 5px;
    background-color: white;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .leaderboard h3 {
    margin-top: 0;
    color: #2196F3;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
  }

  .leaderboard ol {
    list-style-position: inside;
    padding: 0;
    text-align: left;
    max-width: 300px;
    margin: 0 auto;
  }

  .leaderboard li {
    margin-bottom: 5px;
    padding: 8px;
    border-radius: 3px;
    transition: background-color 0.2s;
  }

  .leaderboard li:hover {
    background-color: #f5f5f5;
  }

  .top-score {
    background-color: #fff3cd;
    font-weight: bold;
  }

  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
  }

  .modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    max-width: 300px;
    width: 100%;
  }

  .modal-content h2 {
    margin-top: 0;
    color: #333;
  }

  .modal-content input {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ddd;
    border-radius: 5px;
    box-sizing: border-box;
  }
</style>